package com.own.component.common.base.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import lombok.experimental.FieldNameConstants;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * BaseQuery
 *
 * @author chenxueli
 * @date 2023-07-31 20:09:41
 */
@Schema(title = "查询对象query")
@ToString
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@FieldNameConstants
public class BaseQuery implements Serializable {

    /**
     * 最大行数
     */
    private static final int MAX_ROWS = 100;

    @Schema(title = "关键字")
    private String keywords;

    @Schema(title = "每页显示行数")
    private Integer rows;

    @Schema(title = "页数")
    private Integer page;

    @Schema(title = "查询的主id信息", hidden = true)
    @JsonIgnore
    private List<Long> idList;

    @Schema(title = "是否初始化了", hidden = true)
    @JsonIgnore
    private Boolean init;

    public <T extends BaseQuery> BaseQuery(@NonNull T query) {
        this.rows = query.getRows();
        this.page = query.getPage();
        this.keywords = query.getKeywords();
        this.idList = query.getIdList();
    }

    /**
     * 初始化数据信息
     */
    public void init() {
        if (this.init != null && this.init) {
            return;
        }
        this.idList = new ArrayList<>();
        this.init = true;
        if (this.rows == null || this.rows <= 0) {
            this.rows = 10;
        }
        if (this.page == null || this.page <= 0) {
            this.page = 1;
        }
        if (this.rows > MAX_ROWS) {
            this.rows = 100;
        }
    }

    /**
     * 分页
     */
    public <E> Page<E> page() {
        init();
        return PageHelper.startPage(getPage(), getRows());
    }

    /**
     * 开始行数
     *
     * @return int
     */
    @JsonIgnore
    public int getFrom() {
        init();
        return page * rows - rows;
    }

}
